import { useModel, history, useLocation } from "umi";
import { useEffect } from "react";
import { useReactive, useResponsive } from "ahooks";
import { Layout, Nav } from "@douyinfe/semi-ui";
import Jdenticon from "react-jdenticon";

const { Sider } = Layout;

const PageLeftMenu = ({ leftSiderWidth, onChangeLeftSiderWidth }) => {
    const { routers } = useModel("routers");

    const location = useLocation();
    const responsive = useResponsive();

    const currentRoute = location.pathname.split("/")[1];
    console.log()
    const subMenus = routers[currentRoute].subMenus || [];

    const state = useReactive({
        leftSiderWidth: leftSiderWidth || 160,
        leftSiderCollapsed: true,
        selectedMenuKeys: [],
    });

    useEffect(() => {
        state.leftSiderWidth = state.leftSiderCollapsed ? 60 : leftSiderWidth || 160;
        onChangeLeftSiderWidth(state.leftSiderWidth);
    }, [state.leftSiderCollapsed]);

    useEffect(() => {
        state.leftSiderCollapsed = !responsive.xl;
    }, [responsive]);

    useEffect(() => {
        const pathname = location.pathname.substr(1);
        let paths = pathname.split("/");
        if (paths.length >= 2) {
            state.selectedMenuKeys = [paths[1]];
        }
    }, [location.pathname]);

    return (
        <Sider style={{ backgroundColor: "var(--semi-color-bg-1)" }}>
            <Nav
                selectedKeys={state.selectedMenuKeys}
                style={{ width: state.leftSiderWidth, height: "100%" }}
                footer={{ collapseButton: true }}
                isCollapsed={state.leftSiderCollapsed}
                onCollapseChange={(isCollapsed) => (state.leftSiderCollapsed = isCollapsed)}
                onSelect={({ itemKey, selectedKeys }) => {
                    state.selectedMenuKeys = selectedKeys;
                    let pathname = "/" + currentRoute;
                    pathname += "/" + itemKey;
                    if (subMenus[itemKey].subMenus) {
                        let keys = Object.keys(subMenus[itemKey].subMenus);
                        pathname += "/" + keys[0];
                    }
                    history.replace({ pathname });
                }}
            >
                {Object.keys(subMenus).map((key) => {
                    const item = subMenus[key];
                    return <Nav.Item key={key} itemKey={key} text={item.title} icon={<Jdenticon size="20" value={item.title} />} />;
                })}
            </Nav>
        </Sider>
    );
};

export default PageLeftMenu;
